import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Demo1 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //Scnnner scanner = new Scanner(System.in);
        //Scanner scanner = new Scanner(System.in);
        //Scanner scanner = new Scanner(System.in);
        //Scanner scanner = new Scanner(System.in);
        //-------------------1.进行配置------------------------------------
        //1.DataSource是这个数据库服务器所在的位置
        //2.MysqlDataSource来自于我们导入的这个mysql驱动包
        DataSource dataSource = new MysqlDataSource();
        //向下转型操作，父类转换为子类----低耦合，减少修改导致的bug
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=utf8&&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("808080ZhuZhaoYu#");

        //-----------------2.建立连接--------------------------------------
        Connection connection = dataSource.getConnection();

        //--------------3.构造sql，发给服务器--------------------------------------
        //String sql="insert into student values(18,'zhangsan')";这是直接构造sql语句
        //String sql="delete from student where id =18";

        //String sql="insert into student values("id="+id+"name="+name);
        String sql="insert into student values(?,?)";
//   这不就是占位符拼借吗？
        //int id=scanner.nextInt();
        //String name=scanner.next();
        int id= scanner.nextInt();
        String name =scanner.next();
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        System.out.println("sql="+statement);

        //--------------4.发送sql,执行sql,返回值是整数，表示的是影响的行数
        int n=statement.executeUpdate();
        System.out.println("n="+n);

        //--------------5.释放资源---------------------------------------------
        statement.close();
        connection.close();
    }
}
